package com.fatri.lessionsimple.audio

import android.content.Context
import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioTrack
import java.io.DataInputStream
import java.io.File
import java.io.FileInputStream
import java.lang.IllegalArgumentException
import kotlin.concurrent.thread

class AudioTrackManager {

    companion object {
        val mgr: AudioTrackManager by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { AudioTrackManager() }
    }

    lateinit var ctx: Context

    lateinit var mAudioTrack: AudioTrack

    var bufferSizeInBytes: Int = 0 //缓冲字节数，根据AudioTrack.getMinBufferSize得到

    val sampleFreq: Int = 44100  //采样率 HZ

    val channelConfig: Int = AudioFormat.CHANNEL_OUT_STEREO //双声道

    val audioFormat = AudioFormat.ENCODING_PCM_16BIT //量化编码格式


    val mode = AudioTrack.MODE_STREAM

    fun init(context: Context) {
        ctx = context
        val am: AudioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager

        bufferSizeInBytes = AudioTrack.getMinBufferSize(sampleFreq, channelConfig, audioFormat)


        val attr = AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)  //内容类型
            .setUsage(AudioAttributes.USAGE_MEDIA)      //使用场景
//            .setAllowedCapturePolicy(AudioAttributes.ALLOW_CAPTURE_BY_ALL)  //是否被其他应用捕获
            .build()
        val aFormat =
            AudioFormat.Builder().setSampleRate(sampleFreq).setEncoding(audioFormat).build()

        mAudioTrack =
            AudioTrack(attr, aFormat, bufferSizeInBytes, mode, am.generateAudioSessionId())
    }


    fun play(path: String) {
        val file = File(path)
        if (!file.exists()) {
            throw IllegalArgumentException("文件不存在")
        }
        val dis = DataInputStream(FileInputStream(file))

        thread {
            val byteArray = ByteArray(bufferSizeInBytes)
            var readCount = 0
            while (dis.available() > 0) {
                readCount = dis.read(byteArray)
                if (readCount == AudioTrack.ERROR_INVALID_OPERATION || readCount == AudioTrack.ERROR_BAD_VALUE) {
                    continue;
                }
                if (readCount != 0 && readCount != -1) {
                    if (mAudioTrack.state == AudioTrack.STATE_UNINITIALIZED) init(ctx) //当停止播放时audiotrack释放，重新初始化
                    mAudioTrack.play()
                    mAudioTrack.write(byteArray, 0, readCount)

                }


            }

        }
    }
}